package com.masterclient.app.businessmodule.usermodule.login.contract;

import android.support.annotation.NonNull;
import android.text.TextUtils;

import com.eoner.baselib.presenter.ThrowableConsumer;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.common.bean.base.CommonBaseBean;
import com.eoner.common.config.Config;
import com.masterclient.app.businessmodule.usermodule.api.UserHttpService;
import com.eoner.baselibrary.utils.EncryptUtil;
import com.masterclient.app.businessmodule.usermodule.login.beans.AuthBindNewBean;
import com.masterclient.app.businessmodule.usermodule.login.beans.CaptchaBean;
import com.masterclient.app.businessmodule.usermodule.login.beans.InviteInfoBean;
import com.masterclient.app.businessmodule.usermodule.login.beans.LoginResultBean;
import com.masterclient.app.utils.CaptchaUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.RequestBody;

/**
* Created by TMVPHelper on 2017/07/12
*/
public class QuickLoginPresenter extends QuickLoginContract.Presenter{

    @Override
    public void getCaptcha(@NonNull String phoneNum,@NonNull String type,String ne) {
        mView.baseShowCommitLoading("");
        String captchaValidate = "";
        if (CaptchaUtil.CAPTCHA_NUMBER_TIMES >= Config.CAPTCHA_MAX_TIMES){
            Map<String,String> map = new HashMap<>();
            map.put("failureNum","3");
            map.put("clientTime",System.currentTimeMillis()/1000+"");
            captchaValidate = EncryptUtil.encryptRSA(new Gson().toJson(map),Config.captchaKey);
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile",phoneNum);
            jsonObject.put("type",type);
            jsonObject.put("NECaptchaValidate",ne);
            jsonObject.put("captchaValidate",captchaValidate);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<CaptchaBean> observable = UserHttpService.getInstance().getCaptcha(body);
        Disposable disposable = toSubscribe(observable, new Consumer<CaptchaBean>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull CaptchaBean bean) throws Exception {
                mView.baseHiddenCommitLoading();
                if("0".equals(bean.getCode())){
                    mView.getCaptchaResult("" + true);
                }else {
                    mView.showError(bean.getMsg());
                }
            }
        },new ThrowableConsumer(){
            @Override
            public void accept(@io.reactivex.annotations.NonNull Throwable o) throws Exception {
                mView.baseHiddenCommitLoading();
                super.accept(o);
                mView.showError("获取验证码失败");
            }
        });
        mRxManager.add(disposable);
    }

    @Override
    public void quickLogin(@NonNull String mobile, @NonNull String captcha,String uid,String inviter_code) {
        mView.baseShowCommitLoading("");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile",mobile);
            jsonObject.put("captcha",captcha);
            jsonObject.put("uid",uid);
            jsonObject.put("invite_code","");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<LoginResultBean> observable = UserHttpService.getInstance().quickLogin(body);
        Disposable disposable = toSubscribe(observable, new Consumer<LoginResultBean>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull LoginResultBean bean) throws Exception {
                mView.baseHiddenCommitLoading();
                if("0".equals(bean.getCode())){
                    mView.showLogin(bean.getData());
                }else {
                   mView.showLoginFail(bean.getMsg(),bean.getData()==null||
                           TextUtils.isEmpty(bean.getData().getS_fail_reason())?bean.getMsg():bean.getData().getS_fail_reason());
                }
            }
        },new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.baseHiddenCommitLoading();
                ToastUtil.showToast(WEB_FAILED_STR);
            }
        });
        mRxManager.add(disposable);
    }

    @Override
    public void checkCaptcha(@NonNull String captcha, @NonNull String mobile,String type) {
        mView.baseShowCommitLoading("");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile",mobile);
            jsonObject.put("captcha",captcha);
            jsonObject.put("type",type);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<CommonBaseBean> observable = UserHttpService.getInstance().checkCaptcha(body);
        Disposable disposable = toSubscribe(observable, new Consumer<CommonBaseBean>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull CommonBaseBean bean) throws Exception {
                mView.baseHiddenCommitLoading();
                if("0".equals(bean.getCode())){
                    mView.checkSuccess();
                }else {
                    mView.checkError(bean.getMsg());
                }
            }
        },new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.baseHiddenCommitLoading();
            }
        });
        mRxManager.add(disposable);
    }

    @Override
    public void authLogin(String auth_type, String head_url, String nickname, String union_id,String uid,String inviter_code) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("auth_type",auth_type);
            jsonObject.put("head_url",head_url);
            jsonObject.put("nick_name",nickname);
            jsonObject.put("union_id",union_id);
            jsonObject.put("uid",uid);
            jsonObject.put("invite_code",inviter_code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<LoginResultBean> observable = UserHttpService.getInstance().authLogin(body);
        Disposable disposable = toSubscribe(observable, new Consumer<LoginResultBean>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull LoginResultBean bean) throws Exception {

                if("0".equals(bean.getCode())){
                    mView.authLoginData(bean.getData());
                }else {
                    mView.authLoginError(bean.getMsg(),bean.getData()==null||
                            TextUtils.isEmpty(bean.getData().getS_fail_reason())?bean.getMsg():bean.getData().getS_fail_reason());
                }
            }
        },new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.authLoginError(WEB_FAILED_STR, null);
            }
        });
        mRxManager.add(disposable);
    }

    @Override
    public void getInviteInfo(String invite_code) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("invite_code",invite_code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<InviteInfoBean> observable = UserHttpService.getInstance().getInviteInfo(body);
        Disposable disposable = toSubscribe(observable, new Consumer<InviteInfoBean>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull InviteInfoBean bean) throws Exception {

                if("0".equals(bean.getCode())){
                    mView.showInviteInfo(bean.getData());
                }else {
                    mView.showInviteInfoFail(bean.getMsg());
                }
            }
        },new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.showInviteInfoFail(WEB_FAILED_STR);
            }
        });
        mRxManager.add(disposable);

    }

    @Override
    public void authBind(String auth_type, String mobile, String union_id, String invite_id, String uid, String nick_name, String headimgurl,String nonce,String customer_id,String reward_id) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("auth_type",auth_type);
            jsonObject.put("mobile",mobile);
            jsonObject.put("union_id",union_id);
            jsonObject.put("invite_code",invite_id);
            jsonObject.put("uid",uid);
            jsonObject.put("nick_name",nick_name);
            jsonObject.put("headimgurl",headimgurl);
            jsonObject.put("nonce",nonce);
            jsonObject.put("customer_id",customer_id);
            jsonObject.put("reward_id",reward_id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                jsonObject.toString());
        Observable<AuthBindNewBean> observable = UserHttpService.getInstance().authBind(body);
        Disposable disposable = toSubscribe(observable, new Consumer<AuthBindNewBean>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull AuthBindNewBean bean) throws Exception {

                if("0".equals(bean.getCode())){
                    mView.authBindSuccess(bean.getCode(),bean.getData(),bean.getMsg(),invite_id);
                }else if ("30000".equals(bean.getCode())){
                    mView.authBindSuccess(bean.getCode(),bean.getData(),bean.getMsg(),invite_id);
                }else {
                    mView.authBindFailded(bean.getMsg());
                }
            }
        },new ThrowableConsumer(){
            @Override
            public void accept(Throwable o) throws Exception {
                super.accept(o);
                mView.authBindFailded(WEB_FAILED_STR);
            }
        });
        mRxManager.add(disposable);
    }

}